/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package assignment3;

/**
 *
 * @author Burhan
 */
public class ShuffleCipher implements MessageDecoder, MessageEncoder{

    int n;

    public ShuffleCipher(int n)throws NumberFormatException {
        this.n = n;
    }
    



    

    public String decode(String cipherText) {
        char[] temp = new char[cipherText.length()];
        cipherText.getChars(0, cipherText.length(), temp, 0);
        
        for(int i = 0;i<n;i++)
        {
            char[] firstHalf = new char[(int) Math.round((double) temp.length/2)];
            char[] secondHalf = new char[temp.length-(int) Math.round((double) temp.length/2)];
            
            int indexOfFirstHalf=0;
            int indexOfSecondHalf=0;

            for(int j = 0;j<temp.length;j++)
            {
                if(j%2==0)
                {
                    firstHalf[indexOfFirstHalf] =temp[j];
                    indexOfFirstHalf++;

                }
                else
                {
                    secondHalf[indexOfSecondHalf] = temp[j];
                    indexOfSecondHalf++;
                }

                

            }
            int p = 0;
            int r = 0;

            for(int k = 0;k<temp.length;k++)
            {
                if(k<firstHalf.length)
                {
                    temp[k] = firstHalf[p];
                    p++;
                }
                else
                {
                    temp[k] = secondHalf[r];
                    r++;
                }
            }
        }
        String decodedText = new String(temp);
        return decodedText;
    }

    public String encode(String plainText) {
        char[] temp = new char[plainText.length()];
        plainText.getChars(0, plainText.length(), temp, 0);
        String tempString = new String(temp);
        for(int i = 0;i<n;i++)
        {
            char[] firstHalf = new char[(int) Math.round((double) tempString.length()/2)];
            char[] secondHalf = new char[tempString.length()-(int) Math.round((double) tempString.length()/2)];

            tempString.getChars(0, firstHalf.length, firstHalf, 0);
            tempString.getChars(firstHalf.length, tempString.length(), secondHalf, 0);

            int indexOfFirstHalf=0;
            int indexOfSecondHalf=0;

            for(int j = 0;j<tempString.length();j++)
            {
                if(j%2==0)
                {
                    temp[j] = firstHalf[indexOfFirstHalf];
                    indexOfFirstHalf++;

                }
                else
                {
                    temp[j] = secondHalf[indexOfSecondHalf];
                    indexOfSecondHalf++;
                }

                tempString = String.copyValueOf(temp);



            }
        }
        String decodedText = new String(temp);
        return decodedText;
    }

}
